package com.txzt.gaea.aspect;

import com.txzt.gaea.base.service.DataPermissionService;
import com.txzt.gaea.common.core.base.context.AdminUserContext;
import com.txzt.gaea.common.enums.DataPermissionTypeEnum;
import com.txzt.gaea.vo.AdminUserVO;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * @author :  cong.fang
 * @since :  2022/9/30 20:29
 */
@Aspect
@Component
public class DataPermissionAspect {

    @Autowired
    private DataPermissionService dataPermissionService;

    @Pointcut("@annotation(com.txzt.gaea.aspect.annotation.SysDataPermission)")
    public void sequencePointCut() {
    }

    @Around("sequencePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        AdminUserVO user = AdminUserContext.getUser();
        Integer level = dataPermissionService.getDataPermissionLevel();
        //仅个人数据权限
        if (level.equals(DataPermissionTypeEnum.ONLY_SELF.getCode())) {
            for (Object obj : point.getArgs()) {
                for (Field field : obj.getClass().getDeclaredFields()) {
                    setFieldValue(user, obj, field);
                }
            }
        //本部门数据权限
        } else if (level.equals(DataPermissionTypeEnum.ONLY_DEPT.getCode())) {
            for (Object obj : point.getArgs()) {
                for (Field field : obj.getClass().getDeclaredFields()) {
                    setFieldValue(user, obj, field);
                    if ("permissionDept".equals(field.getName())) {
                        field.setAccessible(true);
                        field.set(obj, user.getDeptid());
                        field.setAccessible(false);
                    }
                }
            }
        //全机构数据权限
        } else {
            for (Object obj : point.getArgs()) {
                for (Field field : obj.getClass().getDeclaredFields()) {
                    if ("currentUser".equals(field.getName())) {
                        field.setAccessible(true);
                        field.set(obj, user.getId());
                        field.setAccessible(false);
                    }
                }
            }
        }
        return point.proceed();
    }

    private void setFieldValue(AdminUserVO user, Object obj, Field field) throws IllegalAccessException {
        if ("currentUser".equals(field.getName())) {
            field.setAccessible(true);
            field.set(obj, user.getId());
            field.setAccessible(false);
        }
        if ("permissionUser".equals(field.getName())) {
            field.setAccessible(true);
            field.set(obj, user.getId());
            field.setAccessible(false);
        }
    }
}
